package com.studyweb.service.impl;

import com.studyweb.pojo.entity.*;
import com.studyweb.mapper.CommonSenseQuestionMapper;
import com.studyweb.mapper.DataAnalysisQuestionMapper;
import com.studyweb.mapper.JudgmentQuestionMapper;
import com.studyweb.mapper.LanguageQuestionMapper;
import com.studyweb.mapper.PoliticsQuestionMapper;
import com.studyweb.mapper.QuantitativeQuestionMapper;
import com.studyweb.service.QuestionImportService;
import com.studyweb.service.impl.ImportResultException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;

import jakarta.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 题目导入服务实现类
 */
@Slf4j
@Service
public class QuestionImportServiceImpl implements QuestionImportService {

    @Autowired
    private PoliticsQuestionMapper politicsQuestionMapper;
    
    @Autowired
    private CommonSenseQuestionMapper commonSenseQuestionMapper;
    
    @Autowired
    private QuantitativeQuestionMapper quantitativeQuestionMapper;
    
    @Autowired
    private JudgmentQuestionMapper judgmentQuestionMapper;
    
    @Autowired
    private DataAnalysisQuestionMapper dataAnalysisQuestionMapper;
    
    @Autowired
    private LanguageQuestionMapper languageQuestionMapper;

    
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 从Excel文件导入题目
     * @param file Excel文件
     * @param moduleType 模块类型（如politics, commonsense等）
     * @param category 分类
     * @param subCategory 子分类
     * @param userId 用户ID
     * @return 成功导入的题目数量
     * @throws Exception 导入过程中发生的异常
     */
    @Override
    public int importQuestionsFromExcel(MultipartFile file, String moduleType, String category, String subCategory, Long userId) throws Exception {
        if (moduleType == null || moduleType.trim().isEmpty()) {
            throw new IllegalArgumentException("模块类型不能为空");
        }
        moduleType = moduleType.trim().toLowerCase();
        if (!isValidModuleType(moduleType)) {
            throw new IllegalArgumentException("不支持的模块类型: " + moduleType);
        }
        log.info("开始导入Excel文件，模块类型: {}, 分类: {}, 子分类: {}", moduleType, category, subCategory);
        try (InputStream is = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0);
            
            List<Object> questions = new ArrayList<>();
            List<String> duplicateIds = new ArrayList<>(); // 用于收集重复ID
            int rowCount = 0;

            // 跳过表头行
            for (Row row : sheet) {
                if (rowCount == 0) {
                    rowCount++;
                    continue;
                }

                // 读取Excel单元格数据
                // 新的表头顺序: ID, 标题, 题目内容, 题型, 难度, 选项A, 选项B, 选项C, 选项D, 正确答案, 解析, 分类, 子分类
                Cell idCell = row.getCell(0); // ID (导入时可以忽略)
                Cell titleCell = row.getCell(1); // 标题
                Cell contentCell = row.getCell(2); // 题目内容
                Cell typeCell = row.getCell(3); // 题型
                Cell difficultyCell = row.getCell(4); // 难度
                Cell optionACell = row.getCell(5); // 选项A
                Cell optionBCell = row.getCell(6); // 选项B
                Cell optionCCell = row.getCell(7); // 选项C
                Cell optionDCell = row.getCell(8); // 选项D
                Cell answerCell = row.getCell(9); // 正确答案
                Cell explanationCell = row.getCell(10); // 解析
                Cell categoryCell = row.getCell(11); // 分类
                Cell subCategoryCell = row.getCell(12); // 子分类

                // 构建选项JSON
                Map<String, String> optionsMap = new HashMap<>();
                optionsMap.put("A", getCellValueAsString(optionACell));
                optionsMap.put("B", getCellValueAsString(optionBCell));
                optionsMap.put("C", getCellValueAsString(optionCCell));
                optionsMap.put("D", getCellValueAsString(optionDCell));
                String optionsJson = objectMapper.writeValueAsString(optionsMap);

                // 获取ID值（如果存在）
                Long id = null;
                try {
                    String idStr = getCellValueAsString(idCell);
                    if (idStr != null && !idStr.trim().isEmpty()) {
                        id = Long.parseLong(idStr.trim());
                    }
                } catch (NumberFormatException e) {
                    log.warn("ID格式不正确，将自动生成ID: {}", e.getMessage());
                }

                // 获取分类和子分类值（如果Excel中有提供，则优先使用Excel中的值，否则使用接口传入的值）
                String excelCategory = getCellValueAsString(categoryCell);
                String excelSubCategory = getCellValueAsString(subCategoryCell);
                
                String finalCategory = (excelCategory != null && !excelCategory.trim().isEmpty()) ? 
                                       excelCategory.trim() : category;
                String finalSubCategory = (excelSubCategory != null && !excelSubCategory.trim().isEmpty()) ? 
                                          excelSubCategory.trim() : subCategory;

                // 根据moduleType创建对应的题目对象
                Object question = createQuestion(
                    moduleType,
                    getCellValueAsString(contentCell),
                    convertQuestionType(getCellValueAsString(typeCell)),
                    getCellValueAsString(difficultyCell),
                    optionsJson,
                    getCellValueAsString(answerCell),
                    getCellValueAsString(explanationCell),
                    getCellValueAsString(titleCell), // 标题
                    finalCategory, // 分类（优先使用Excel中的值）
                    finalSubCategory, // 子分类（优先使用Excel中的值）
                    userId,
                    id // 传递ID值
                );

                if (question != null) {
                    questions.add(question);
                }
                rowCount++;
            }

            // 批量插入题目，并收集重复ID信息
            int successCount = 0;
            for (Object question : questions) {
                try {
                    insertQuestion(moduleType, question);
                    successCount++;
                } catch (Exception e) {
                    // 检查是否是主键冲突异常
                    if (e.getMessage() != null && e.getMessage().contains("Duplicate entry")) {
                        // 提取重复的ID
                        String duplicateId = extractDuplicateId(e.getMessage());
                        if (duplicateId != null) {
                            duplicateIds.add(duplicateId);
                        } else {
                            // 如果无法提取具体ID，添加通用重复标识
                            duplicateIds.add("未知ID");
                        }
                        log.warn("跳过重复题目，ID: {}", duplicateId);
                    } else {
                        // 如果是其他异常，重新抛出
                        throw e;
                    }
                }
            }

            // 构建返回消息
            StringBuilder message = new StringBuilder();
            message.append("成功导入 ").append(successCount).append(" 道题目");
            
            if (!duplicateIds.isEmpty()) {
                message.append("，跳过 ").append(duplicateIds.size()).append(" 道重复题目");
                // 如果重复题目不多，列出具体的ID
                if (duplicateIds.size() <= 10) {
                    message.append(" (ID: ").append(String.join(", ", duplicateIds)).append(")");
                }
            }

            log.info("Excel导入完成，{}", message.toString());
            // 返回自定义消息而不是简单的数量
            throw new ImportResultException(message.toString(), successCount, duplicateIds);
        } catch (ImportResultException ire) {
            // 这是我们自定义的异常，用于返回导入结果信息
            return ire.getImportedCount();
        } catch (Exception e) {
            log.error("Excel导入失败: {}", e.getMessage(), e);
            
            // 检查是否是主键冲突异常
            if (e.getMessage() != null && e.getMessage().contains("Duplicate entry")) {
                // 提取重复的ID
                String duplicateId = extractDuplicateId(e.getMessage());
                if (duplicateId != null) {
                    throw new Exception("导入失败：题目ID " + duplicateId + " 已存在，请检查Excel文件中的ID列，避免重复导入相同ID的题目");
                } else {
                    throw new Exception("导入失败：Excel文件中包含已存在的题目ID，请检查ID列，避免重复导入");
                }
            }
            
            throw new Exception("Excel导入失败: " + e.getMessage());
        }
    }
    
    /**
     * 从错误消息中提取重复的ID
     * @param errorMessage 错误消息
     * @return 重复的ID，如果无法提取则返回null
     */
    private String extractDuplicateId(String errorMessage) {
        try {
            // 匹配 "Duplicate entry '73' for key" 格式的ID
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("Duplicate entry '([^']+)' for key");
            java.util.regex.Matcher matcher = pattern.matcher(errorMessage);
            if (matcher.find()) {
                return matcher.group(1);
            }
        } catch (Exception e) {
            log.warn("提取重复ID失败: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 根据模块类型创建题目对象
     * @param moduleType 模块类型
     * @param content 题目内容
     * @param questionType 题型
     * @param difficulty 难度
     * @param options 选项（JSON格式）
     * @param correctAnswer 正确答案
     * @param explanation 题目解析
     * @param title 题目标题
     * @param category 分类
     * @param subCategory 子分类
     * @param userId 用户ID
     * @param id 题目ID（可选）
     * @return 创建的题目对象
     */
    private Object createQuestion(String moduleType, String content, String questionType,
                                String difficulty, String options, String correctAnswer,
                                String explanation, String title, String category, String subCategory,
                                Long userId, Long id) {
        log.info("创建题目对象，模块类型: {}, 题型: {}, 难度: {}, 分类: {}, 子分类: {}", moduleType, questionType, difficulty, category, subCategory);
        LocalDateTime now = LocalDateTime.now();
        
        String type = moduleType.toLowerCase().trim();
        switch (type) {
            case "politics":
                PoliticsQuestion politicsQuestion = new PoliticsQuestion();
                politicsQuestion.setQuestionId(id); // 设置ID
                politicsQuestion.setContent(content);
                politicsQuestion.setTitle(title);
                politicsQuestion.setQuestionType(questionType);
                politicsQuestion.setDifficulty(difficulty);
                politicsQuestion.setOptions(options);
                politicsQuestion.setCorrectAnswer(correctAnswer);
                politicsQuestion.setExplanation(explanation);
                politicsQuestion.setUserId(userId);
                politicsQuestion.setCreateTime(now);
                politicsQuestion.setUpdateTime(now);
                politicsQuestion.setStatus(1);
                // 时政模块使用category作为时间字段
                politicsQuestion.setCategory(category);
                return politicsQuestion;

            case "commonsense":
                CommonSenseQuestion commonSenseQuestion = new CommonSenseQuestion();
                commonSenseQuestion.setQuestionId(id); // 设置ID
                commonSenseQuestion.setContent(content);
                commonSenseQuestion.setTitle(title);
                commonSenseQuestion.setQuestionType(questionType);
                commonSenseQuestion.setDifficulty(difficulty);
                commonSenseQuestion.setOptions(options);
                commonSenseQuestion.setCorrectAnswer(correctAnswer);
                commonSenseQuestion.setExplanation(explanation);
                commonSenseQuestion.setUserId(userId);
                commonSenseQuestion.setCreateTime(now);
                commonSenseQuestion.setUpdateTime(now);
                commonSenseQuestion.setStatus(1);
                commonSenseQuestion.setCategory(category);
                commonSenseQuestion.setSubCategory(subCategory);
                return commonSenseQuestion;

            case "quantity":
                QuantitativeQuestion quantitativeQuestion = new QuantitativeQuestion();
                quantitativeQuestion.setQuestionId(id); // 设置ID
                quantitativeQuestion.setContent(content);
                quantitativeQuestion.setTitle(title);
                quantitativeQuestion.setQuestionType(questionType);
                quantitativeQuestion.setDifficulty(difficulty);
                quantitativeQuestion.setOptions(options);
                quantitativeQuestion.setCorrectAnswer(correctAnswer);
                quantitativeQuestion.setExplanation(explanation);
                quantitativeQuestion.setUserId(userId);
                quantitativeQuestion.setCreateTime(now);
                quantitativeQuestion.setUpdateTime(now);
                quantitativeQuestion.setStatus(1);
                quantitativeQuestion.setCategory(category);
                quantitativeQuestion.setSubCategory(subCategory);
                return quantitativeQuestion;

            case "judgment":
                JudgmentQuestion judgmentQuestion = new JudgmentQuestion();
                judgmentQuestion.setQuestionId(id); // 设置ID
                judgmentQuestion.setContent(content);
                judgmentQuestion.setTitle(title);
                judgmentQuestion.setQuestionType(questionType);
                judgmentQuestion.setDifficulty(difficulty);
                judgmentQuestion.setOptions(options);
                judgmentQuestion.setCorrectAnswer(correctAnswer);
                judgmentQuestion.setExplanation(explanation);
                judgmentQuestion.setUserId(userId);
                judgmentQuestion.setCreateTime(now);
                judgmentQuestion.setUpdateTime(now);
                judgmentQuestion.setStatus(1);
                judgmentQuestion.setCategory(category);
                judgmentQuestion.setSubCategory(subCategory);
                return judgmentQuestion;

            case "dataanalysis":
                DataAnalysisQuestion dataAnalysisQuestion = new DataAnalysisQuestion();
                dataAnalysisQuestion.setQuestionId(id); // 设置ID
                dataAnalysisQuestion.setContent(content);
                dataAnalysisQuestion.setTitle(title);
                dataAnalysisQuestion.setQuestionType(questionType);
                dataAnalysisQuestion.setDifficulty(difficulty);
                dataAnalysisQuestion.setOptions(options);
                dataAnalysisQuestion.setCorrectAnswer(correctAnswer);
                dataAnalysisQuestion.setExplanation(explanation);
                dataAnalysisQuestion.setUserId(userId);
                dataAnalysisQuestion.setCreateTime(now);
                dataAnalysisQuestion.setUpdateTime(now);
                dataAnalysisQuestion.setStatus(1);
                dataAnalysisQuestion.setCategory(category);
                dataAnalysisQuestion.setSubCategory(subCategory);
                return dataAnalysisQuestion;
                
            case "language":
                LanguageQuestion languageQuestion = new LanguageQuestion();
                languageQuestion.setQuestionId(id); // 设置ID
                languageQuestion.setContent(content);
                languageQuestion.setTitle(title);
                languageQuestion.setQuestionType(questionType);
                languageQuestion.setDifficulty(difficulty);
                languageQuestion.setOptions(options);
                languageQuestion.setCorrectAnswer(correctAnswer);
                languageQuestion.setExplanation(explanation);
                languageQuestion.setUserId(userId);
                languageQuestion.setCreateTime(now);
                languageQuestion.setUpdateTime(now);
                languageQuestion.setStatus(1);
                languageQuestion.setCategory(category);
                languageQuestion.setSubCategory(subCategory);
                return languageQuestion;

            default:
                log.error("不支持的题目类型: {}", moduleType);
                return null;
        }
    }

    /**
     * 根据模块类型创建题目对象（重载方法，保持向后兼容）
     * @param moduleType 模块类型
     * @param content 题目内容
     * @param questionType 题型
     * @param difficulty 难度
     * @param options 选项（JSON格式）
     * @param correctAnswer 正确答案
     * @param explanation 题目解析
     * @param title 题目标题
     * @param category 分类
     * @param subCategory 子分类
     * @param userId 用户ID
     * @return 创建的题目对象
     */
    private Object createQuestion(String moduleType, String content, String questionType,
                                String difficulty, String options, String correctAnswer,
                                String explanation, String title, String category, String subCategory,
                                Long userId) {
        return createQuestion(moduleType, content, questionType, difficulty, options, 
                            correctAnswer, explanation, title, category, subCategory, userId, null);
    }

    /**
     * 插入题目到数据库
     * @param moduleType 模块类型
     * @param question 题目对象
     */
    private void insertQuestion(String moduleType, Object question) throws Exception {
        log.info("插入题目，模块类型: {}, 题目类型: {}", moduleType, question.getClass().getSimpleName());
        String type = moduleType.toLowerCase().trim();
        switch (type) {
            case "politics":
                politicsQuestionMapper.insert((PoliticsQuestion) question);
                break;
            case "commonsense":
                commonSenseQuestionMapper.insert((CommonSenseQuestion) question);
                break;
            case "quantity":
                quantitativeQuestionMapper.insert((QuantitativeQuestion) question);
                break;
            case "judgment":
                judgmentQuestionMapper.insert((JudgmentQuestion) question);
                break;
            case "dataanalysis":
                dataAnalysisQuestionMapper.insert((DataAnalysisQuestion) question);
                break;
            case "language":
                log.info("插入题目，模块类型: {}, 题目类型: {}", moduleType, "LanguageQuestion");
                languageQuestionMapper.insert((LanguageQuestion) question);
                break;
            default:
                log.error("不支持的题目类型: {}", moduleType);
        }
    }

    /**
     * 获取单元格内容并转换为字符串
     * @param cell 单元格对象
     * @return 单元格内容的字符串表示
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    /**
     * 检查模块类型是否有效
     * @param moduleType 模块类型
     * @return 如果模块类型有效则返回true，否则返回false
     */
    private boolean isValidModuleType(String moduleType) {
        return moduleType.equals("politics") ||
               moduleType.equals("commonsense") ||
               moduleType.equals("quantity") ||
               moduleType.equals("judgment") ||
               moduleType.equals("dataanalysis") ||
               moduleType.equals("language") ||
               moduleType.equals("graphicreasoning");
    }

    /**
     * 将Excel中的题型转换为系统内部的题型表示
     * @param excelType Excel中的题型字符串
     * @return 转换后的系统内部题型字符串
     */
    private String convertQuestionType(String excelType) {
        switch (excelType.toLowerCase()) {
            case "single":
                return "single_choice";
            case "multiple":
                return "multiple_choice";
            case "judge":
                return "true_false";
            case "fill":
                return "fill_blank";
            default:
                return excelType;
        }
    }

    @Override
    public void exportQuestionsToExcel(String keyword, String difficulty, String questionType, String module, String category, String subCategory, HttpServletResponse response) throws Exception {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"questions_export.xlsx\"");
        
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("题目导出");
        
        // 创建居中对齐样式
        CellStyle centerStyle = workbook.createCellStyle();
        centerStyle.setAlignment(HorizontalAlignment.CENTER);
        centerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        
        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"ID", "标题", "题目内容", "题型", "难度", "选项A", "选项B", "选项C", "选项D", "正确答案", "解析", "分类", "子分类"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(centerStyle); // 应用居中样式
        }
        
        // 设置列宽
        sheet.setColumnWidth(0, 15 * 256);   // ID列
        sheet.setColumnWidth(1, 20 * 256);   // 标题列
        sheet.setColumnWidth(2, 50 * 256);   // 题目内容列
        sheet.setColumnWidth(3, 15 * 256);   // 题型列
        sheet.setColumnWidth(4, 15 * 256);   // 难度列
        sheet.setColumnWidth(5, 30 * 256);   // 选项A列
        sheet.setColumnWidth(6, 30 * 256);   // 选项B列
        sheet.setColumnWidth(7, 30 * 256);   // 选项C列
        sheet.setColumnWidth(8, 30 * 256);   // 选项D列
        sheet.setColumnWidth(9, 20 * 256);   // 正确答案列
        sheet.setColumnWidth(10, 40 * 256);  // 解析列
        sheet.setColumnWidth(11, 20 * 256);  // 分类列
        sheet.setColumnWidth(12, 20 * 256);  // 子分类列
        
        // 根据模块类型查询数据并写入Excel
        int rowNum = 1;
        if (module != null && !module.isEmpty()) {
            log.info("导出题目，模块类型: {}, 题型: {}, 难度: {}, 分类: {}, 子分类: {}, 关键词: {}", 
                     module, questionType, difficulty, category, subCategory, keyword);
            switch (module.toLowerCase()) {
                case "commonsense":
                    List<CommonSenseQuestion> commonSenseQuestions = commonSenseQuestionMapper.selectAllQuestions(questionType, difficulty, category, subCategory, keyword, "question_id", "asc");
                    log.info("查询到常识题目数量: {}", commonSenseQuestions.size());
                    for (CommonSenseQuestion question : commonSenseQuestions) {
                        writeQuestionToRow(sheet.createRow(rowNum++), question, centerStyle);
                    }
                    break;
                case "politics":
                    List<PoliticsQuestion> politicsQuestions = politicsQuestionMapper.selectAllQuestions(questionType, difficulty, category, subCategory, keyword, "question_id", "asc");
                    log.info("查询到时政题目数量: {}", politicsQuestions.size());
                    for (PoliticsQuestion question : politicsQuestions) {
                        writeQuestionToRow(sheet.createRow(rowNum++), question, centerStyle);
                    }
                    break;
                case "quantity":
                    List<QuantitativeQuestion> quantitativeQuestions = quantitativeQuestionMapper.selectAllQuestions(questionType, difficulty, category, subCategory, keyword, "question_id", "asc");
                    log.info("查询到数量题目数量: {}", quantitativeQuestions.size());
                    for (QuantitativeQuestion question : quantitativeQuestions) {
                        writeQuestionToRow(sheet.createRow(rowNum++), question, centerStyle);
                    }
                    break;
                case "judgment":
                    List<JudgmentQuestion> judgmentQuestions = judgmentQuestionMapper.selectAllQuestions(questionType, difficulty, category, subCategory, keyword, "question_id", "asc");
                    log.info("查询到判断题目数量: {}", judgmentQuestions.size());
                    for (JudgmentQuestion question : judgmentQuestions) {
                        writeQuestionToRow(sheet.createRow(rowNum++), question, centerStyle);
                    }
                    break;
                case "dataanalysis":
                    List<DataAnalysisQuestion> dataAnalysisQuestions = dataAnalysisQuestionMapper.selectAllQuestions(questionType, difficulty, category, subCategory, keyword, "question_id", "asc");
                    log.info("查询到资料分析题目数量: {}", dataAnalysisQuestions.size());
                    for (DataAnalysisQuestion question : dataAnalysisQuestions) {
                        writeQuestionToRow(sheet.createRow(rowNum++), question, centerStyle);
                    }
                    break;
                case "language":
                    List<LanguageQuestion> languageQuestions = languageQuestionMapper.selectAllQuestions(questionType, difficulty, category, subCategory, keyword, "question_id", "asc");
                    log.info("查询到言语题目数量: {}", languageQuestions.size());
                    for (LanguageQuestion question : languageQuestions) {
                        writeQuestionToRow(sheet.createRow(rowNum++), question, centerStyle);
                    }
                    break;
                default:
                    log.warn("不支持的模块类型: {}", module);
                    // 不支持的模块类型，不写入数据
                    break;
            }
        } else {
            log.warn("模块类型为空");
        }
        
        // 写入响应
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
    }
    
    /**
     * 将题目数据写入Excel行
     * @param row Excel行
     * @param question 题目对象
     * @param centerStyle 居中对齐样式
     */
    private void writeQuestionToRow(Row row, Object question, CellStyle centerStyle) {
        try {
            log.debug("写入题目到Excel行: {}", question);
            // 使用反射获取题目属性
            Class<?> clazz = question.getClass();
            
            // 获取ID
            java.lang.reflect.Method getIdMethod = clazz.getMethod("getQuestionId");
            Long id = (Long) getIdMethod.invoke(question);
            Cell idCell = row.createCell(0);
            idCell.setCellValue(id != null ? id.toString() : "");
            idCell.setCellStyle(centerStyle); // 应用居中样式
            
            // 获取标题
            String title = "";
            try {
                java.lang.reflect.Method getTitleMethod = clazz.getMethod("getTitle");
                title = (String) getTitleMethod.invoke(question);
            } catch (NoSuchMethodException e) {
                // 如果没有getTitle方法，标题为空
                title = "";
            }
            Cell titleCell = row.createCell(1);
            titleCell.setCellValue(title != null ? title : "");
            titleCell.setCellStyle(centerStyle); // 应用居中样式
            
            // 获取题目内容
            java.lang.reflect.Method getContentMethod = clazz.getMethod("getContent");
            String content = (String) getContentMethod.invoke(question);
            row.createCell(2).setCellValue(content);
            
            // 获取题型
            java.lang.reflect.Method getQuestionTypeMethod = clazz.getMethod("getQuestionType");
            String questionType = (String) getQuestionTypeMethod.invoke(question);
            Cell typeCell = row.createCell(3);
            typeCell.setCellValue(questionType);
            typeCell.setCellStyle(centerStyle); // 应用居中样式
            
            // 获取难度
            java.lang.reflect.Method getDifficultyMethod = clazz.getMethod("getDifficulty");
            String difficulty = (String) getDifficultyMethod.invoke(question);
            Cell difficultyCell = row.createCell(4);
            difficultyCell.setCellValue(difficulty);
            difficultyCell.setCellStyle(centerStyle); // 应用居中样式
            
            // 获取选项
            java.lang.reflect.Method getOptionsMethod = clazz.getMethod("getOptions");
            String optionsJson = (String) getOptionsMethod.invoke(question);
            if (optionsJson != null && !optionsJson.isEmpty()) {
                try {
                    Map<String, String> options = objectMapper.readValue(optionsJson, new com.fasterxml.jackson.core.type.TypeReference<Map<String, String>>() {});
                    Cell optionACell = row.createCell(5);
                    optionACell.setCellValue(options.getOrDefault("A", ""));
                    optionACell.setCellStyle(centerStyle); // 应用居中样式
                    
                    Cell optionBCell = row.createCell(6);
                    optionBCell.setCellValue(options.getOrDefault("B", ""));
                    optionBCell.setCellStyle(centerStyle); // 应用居中样式
                    
                    Cell optionCCell = row.createCell(7);
                    optionCCell.setCellValue(options.getOrDefault("C", ""));
                    optionCCell.setCellStyle(centerStyle); // 应用居中样式
                    
                    Cell optionDCell = row.createCell(8);
                    optionDCell.setCellValue(options.getOrDefault("D", ""));
                    optionDCell.setCellStyle(centerStyle); // 应用居中样式
                } catch (Exception e) {
                    log.warn("解析选项失败: {}", e.getMessage());
                    // 处理解析错误
                    Cell optionACell = row.createCell(5);
                    optionACell.setCellValue("");
                    optionACell.setCellStyle(centerStyle); // 应用居中样式
                    
                    Cell optionBCell = row.createCell(6);
                    optionBCell.setCellValue("");
                    optionBCell.setCellStyle(centerStyle); // 应用居中样式
                    
                    Cell optionCCell = row.createCell(7);
                    optionCCell.setCellValue("");
                    optionCCell.setCellStyle(centerStyle); // 应用居中样式
                    
                    Cell optionDCell = row.createCell(8);
                    optionDCell.setCellValue("");
                    optionDCell.setCellStyle(centerStyle); // 应用居中样式
                }
            } else {
                Cell optionACell = row.createCell(5);
                optionACell.setCellValue("");
                optionACell.setCellStyle(centerStyle); // 应用居中样式
                
                Cell optionBCell = row.createCell(6);
                optionBCell.setCellValue("");
                optionBCell.setCellStyle(centerStyle); // 应用居中样式
                
                Cell optionCCell = row.createCell(7);
                optionCCell.setCellValue("");
                optionCCell.setCellStyle(centerStyle); // 应用居中样式
                
                Cell optionDCell = row.createCell(8);
                optionDCell.setCellValue("");
                optionDCell.setCellStyle(centerStyle); // 应用居中样式
            }
            
            // 获取正确答案
            java.lang.reflect.Method getCorrectAnswerMethod = clazz.getMethod("getCorrectAnswer");
            String correctAnswer = (String) getCorrectAnswerMethod.invoke(question);
            Cell answerCell = row.createCell(9);
            answerCell.setCellValue(correctAnswer != null ? correctAnswer : "");
            answerCell.setCellStyle(centerStyle); // 应用居中样式
            
            // 获取解析
            java.lang.reflect.Method getExplanationMethod = clazz.getMethod("getExplanation");
            String explanation = (String) getExplanationMethod.invoke(question);
            row.createCell(10).setCellValue(explanation != null ? explanation : "");
            
            // 获取分类
            String category = "";
            try {
                java.lang.reflect.Method getCategoryMethod = clazz.getMethod("getCategory");
                category = (String) getCategoryMethod.invoke(question);
            } catch (NoSuchMethodException e) {
                // 如果没有getCategory方法，分类为空
                category = "";
            }
            Cell categoryCell = row.createCell(11);
            categoryCell.setCellValue(category != null ? category : "");
            categoryCell.setCellStyle(centerStyle); // 应用居中样式
            
            // 获取子分类
            String subCategory = "";
            try {
                java.lang.reflect.Method getSubCategoryMethod = clazz.getMethod("getSubCategory");
                subCategory = (String) getSubCategoryMethod.invoke(question);
            } catch (NoSuchMethodException e) {
                // 如果没有getSubCategory方法，子分类为空
                subCategory = "";
            }
            Cell subCategoryCell = row.createCell(12);
            subCategoryCell.setCellValue(subCategory != null ? subCategory : "");
            subCategoryCell.setCellStyle(centerStyle); // 应用居中样式
        } catch (Exception e) {
            log.error("写入题目数据到Excel行失败: {}", e.getMessage(), e);
            // 发生错误时，填充空值
            for (int i = 0; i < 13; i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue("");
                cell.setCellStyle(centerStyle); // 应用居中样式
            }
        }
    }
    
    // 为保持向后兼容，保留原有的writeQuestionToRow方法
    private void writeQuestionToRow(Row row, Object question) {
        // 创建一个默认的居中样式
        Workbook workbook = row.getSheet().getWorkbook();
        CellStyle centerStyle = workbook.createCellStyle();
        centerStyle.setAlignment(HorizontalAlignment.CENTER);
        centerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        writeQuestionToRow(row, question, centerStyle);
    }
}